#include "../../common/message.hpp"
#include "../../common/net.hpp"
#include "../../common/dispatcher.hpp"

void onRpcRequest(const rpc::BaseConnection::ptr &conn, rpc::RpcRequest::ptr &msg)
{
    LOG(INFO, "收到Rpc请求:method:%s",msg->method().c_str());
    std::string body = msg->serialize();
    std::cout << body << std::endl;
    rpc::RpcResponse::ptr rpc_req = rpc::MessageFactory::create<rpc::RpcResponse>();
    rpc_req->setId("11111");
    rpc_req->setMType(rpc::MType::RSP_RPC);
    rpc_req->setRCode(rpc::RCode::RCODE_OK);
    rpc_req->setResult(33);
    conn->send(rpc_req);
}
void onTopicRequest(const rpc::BaseConnection::ptr &conn, rpc::TopicRequest::ptr &msg)
{
    LOG(INFO, "收到topic请求");
    std::string body = msg->serialize();
    std::cout << body << std::endl;
    rpc::TopicResponse::ptr rpc_req = rpc::MessageFactory::create<rpc::TopicResponse>();
    rpc_req->setId("22222");
    rpc_req->setMType(rpc::MType::RSP_TOPIC);
    rpc_req->setRCode(rpc::RCode::RCODE_OK);

    conn->send(rpc_req);
}

int main()
{
    std::shared_ptr<rpc::Dispatcher> dispatcher = std::make_shared<rpc::Dispatcher>();
    dispatcher->registerHandler<rpc::RpcRequest>(rpc::MType::REQ_RPC, onRpcRequest);
    dispatcher->registerHandler<rpc::TopicRequest>(rpc::MType::REQ_TOPIC, onTopicRequest);
    rpc::BaseServer::ptr server = rpc::ServerFactory::create(9090);
    rpc::MessageCallback message_cb = std::bind(&rpc::Dispatcher::onMessage,dispatcher.get(),std::placeholders::_1,std::placeholders::_2);
    server->setMessageCallback(message_cb);
    server->start();
    return 0;
}